<template>
    <div class="box">
        <el-card class="box-card">
            <template #header>
                <div class="card-header">
                    <span>个人信息</span>
                    <div>
                        <el-button class="button" @click="change">编辑用户</el-button>
                        <el-button class="button" type="danger" @click="updata">修改密码</el-button>
                    </div>
                </div>
            </template>
            <div class="cardbody">
                <div class="touxiang">
                    头像：
                    <el-avatar size="large" :src="userinfo.avatar" />
                </div>
                <div>
                    昵称：
                    <span>{{ userinfo.name }}</span>
                </div>
            </div>
        </el-card>
        <dialogg :istoshow="showemit" title="编辑用户" @cansol="cansol('编辑')" width="30%">
            <template #body>
                <el-form :model="updatainfo" label-width="80px">
                    <el-form-item label="用户名:">
                        <el-input v-model="updatainfo.name" />
                    </el-form-item>
                    <el-form-item label="头像">
                        <upload :limit="1" :multiple="true" :height="80" :width="80" v-model:imglist="updatainfo.avatar">
                        </upload>
                    </el-form-item>
                </el-form>
            </template>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="cansol('编辑')">
                        取消
                    </el-button>
                    <el-button type="primary" @click="sub('编辑')">
                        确定
                    </el-button>
                </span>
            </template>
        </dialogg>
        <dialogg :istoshow="isshowchange" title="编辑用户" @cansol="cansol('密码')" width="30%">
            <template #body>
                <el-form :model="password" label-width="80px">
                    <el-form-item label="旧密码:">
                        <el-input v-model="password.old" />
                    </el-form-item>
                    <el-form-item label="新密码:">
                        <el-input v-model="password.new" />
                    </el-form-item>
                    <el-form-item label="确认密码:">
                        <el-input v-model="password.new2" />
                    </el-form-item>
                </el-form>
            </template>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="cansol('密码')">
                        取消
                    </el-button>
                    <el-button type="primary" @click="sub('密码')">
                        确定
                    </el-button>
                </span>
            </template>
        </dialogg>
    </div>
</template>

<script setup>
import { getuser, updateuser, changepassword, isuser } from '@/api/users.js'
import upload from "@/components/upload.vue"
import dialogg from '@/components/dialog.vue';
import { useRouter } from 'vue-router'
import { Userstore } from '@/store/User.js'
import { ref, onMounted, inject } from 'vue';
import { getQiniuToken } from "@/api/users.js"
import { uploadqiniu, randomString } from "@/util/index.js"
import { deleteimg } from "@/api/friend.js"
import { useBaseStore } from "@/store/Base.js"

let reload = inject('reload')
let userstore = Userstore();
let router = useRouter()
let corver
let showemit = ref(false);
let isshowchange = ref(false)
let baseStore = useBaseStore()
let userinfo = ref({
    name: "",
    avatar: ""
})
let updatainfo = ref({
    name: "",
    avatar: []
})
let password = ref({
    old: "",
    new: "",
    new2: ""
})
function updata() {
    isshowchange.value = true
}
function change() {
    showemit.value = true
    updatainfo.value.name = userinfo.value.name
    updatainfo.value.avatar[0] = {
        url: userinfo.value.avatar,
        name: "1",
    }
    corver = userinfo.value.avatar
}
async function sub(data) {
    if (data == "编辑") {
        if (updatainfo.value.name == "" || updatainfo.value.avatar.length == 0) {
            ElMessage({
                showClose: true,
                message: '请填写数据',
                type: 'warning',
            })
            return
        } else {
            let newimg = ""
            let iscanuser = await isuser({ username: updatainfo.value.name })
            console.log(iscanuser);
            if (iscanuser.data.status == 200) {
                let data = await getQiniuToken();
                /* 获取七牛云的token成功 */
                if (data.data.status == 200) {
                    baseStore.qiniuToken = data.data.data.uploadToken;
                    let ress = await uploadqiniu(updatainfo.value.avatar);
                    if (ress.length !== 0) {
                        newimg = import.meta.env.VITE_API_PHOTO + ress[0].data.key
                        let result = await deleteimg({
                            oldimg: corver.split("/").pop(),
                        })
                    }
                    let res = await updateuser({
                        name: updatainfo.value.name,
                        avatar: newimg == "" ? corver : newimg
                    })
                    if (res.data.status == 200) {
                        userstore.storageUserInfo({
                            Users_name: res.data.data.Users_name,
                            Users_corver: res.data.data.Users_corver,
                            id: res.data.data.id
                        })
                        ElMessage({
                            message: '修改成功',
                            type: 'success',
                        })
                        reload()
                    } else {
                        ElMessage({
                            showClose: true,
                            message: '修改失败',
                            type: 'error',
                        })
                        return
                    }

                }
            } else {

                ElMessage({
                    showClose: true,
                    message: '用户名已存在',
                    type: 'warning',
                })
            }
        }
    } else {
        /* 修改密码 */
        if (password.value.old == "" || password.value.new == "" || password.value.new2 == "") {
            ElMessage({
                showClose: true,
                message: '请填写数据',
                type: 'warning',
            })
            return
        } else {
            if (password.value.new !== password.value.new2) {
                ElMessage({
                    showClose: true,
                    message: '两次密码不正确',
                    type: 'warning',
                })
                return
            } else {
                let res = await changepassword({
                    newpassword: password.value.new,
                    oldpassword: password.value.old
                })
                if (res.data.status == 200) {
                    ElMessage({
                        message: '修改成功',
                        type: 'success'
                    })
                    password.value.old = ""
                    password.value.new = ""
                    password.value.new2 = ""
                    isshowchange.value = false
                } else {
                    ElMessage({
                        showClose: true,
                        message: '修改失败',
                        type: 'error',
                    })
                    return
                }
            }
        }
    }
}
function cansol(data) {
    if (data == "编辑") {
        showemit.value = false
    } else {
        isshowchange.value = false
    }
}
onMounted(async () => {
    let res = await getuser()
    if (res.data.status == 200) {
        userinfo.value.name = res.data.data.Users_name
        userinfo.value.avatar = res.data.data.Users_corver
    } else {
        ElMessage({
            showClose: true,
            message: '用户信息获取失败,请重新登录',
            type: 'warning',
        })
        userstore.clearuserinfo()
        localStorage.removeItem("access_token")
        localStorage.removeItem("refresh_token")
        router.push('/login')
    }
})
</script>

<style lang="css" scoped>
.touxiang {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
}

.cardbody {
    padding: 20px;
}

.box {

    padding: 10px;
    height: 500px;
    display: flex;
    justify-content: center;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.box-card {

    height: 100%;
    width: 48%;
    border: 0px !important;
}

:deep(.el-card__header) {
    padding: 5px 25px !important;
}
</style>